package com.topisv.tms.web;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.google.common.collect.Maps;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.Performance;
import com.topisv.tms.entity.PerformanceFee;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.work.WorkOrderNoCascade;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.PerformanceFeeService;
import com.topisv.tms.service.PerformanceService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 
 * @author 
 */
@Controller
@RequestMapping(value = "/performance")
public class PerformanceController extends BaseDataTableController{

	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private CustomersService customersService;


	@Autowired
	private PerformanceService performanceService;
	@Autowired
	private PerformanceFeeService performanceFeeService;

	@RequestMapping(value = "v2_show")
	public String list(Model model,  ServletRequest request) {
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
		model.addAttribute("warehouseList", warehouseList);
		return "performance/performanceList";
	}
	
	@RequestMapping(value = "page",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			paramHolder.getSearchParams().put("EQ_status", "1");
			Page<Performance> page = performanceService.getPerformance(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "v2_create", method = RequestMethod.GET)
	public String createForm(Model model) {
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
		List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("warehouseList", warehouseList);
		model.addAttribute("customerList", customerList);
		model.addAttribute("performance", new Performance());
		model.addAttribute("action", "create");
		return "performance/performanceForm";
	}
	
	
	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@RequestParam(value = "realname", required = true) String realname,
			@RequestParam(value = "optype", required = true) String optype,
			@RequestParam(value = "warehouseCode", required = true) String warehouseCode,
			@RequestParam(value = "customerCode", required = true) String customerCode,
			@RequestParam(value = "aboutCode", required = true) String aboutCode,
			@RequestParam(value = "qty", required = true) String qty,
			@RequestParam(value = "workTime", required = true) String workTime,
			RedirectAttributes redirectAttributes) throws ParseException {
		Performance performance = new Performance();
		performance.setRealname(realname);
		performance.setWarehouseCode(warehouseCode);
		performance.setCustomerCode(customerCode);
		performance.setOptype(optype);
		performance.setAboutCode(aboutCode);
		performance.setQty(qty);
		performance.setWorkTime(TimeUtil.getDate(workTime));
		performance.setCreater("");
		performance.setStatus("1");
		performance.setCreateTime(new Date());
		performanceService.savePerformance(performance);
		redirectAttributes.addFlashAttribute("message", "创建成功");
		return "redirect:/performance/v2_show";
	}


	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		performanceService.deletPeformance(id);
		redirectAttributes.addFlashAttribute("message", "删除成功");
		return "redirect:/performance/v2_show";
	}
	
	/**
	 * 导出发货清单
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "exportExcel")
	public void exportExcel(ServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			String warehouseCode=(String) request.getParameter("search_EQ_warehouseCode");
			String _fromDate=(String) request.getParameter("_fromDate");
			String _toDate=(String) request.getParameter("_toDate");
			List<Map<String, Object>> listMap = performanceService.getCount(_fromDate, _toDate, warehouseCode);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition","attachment; filename=" + warehouseCode +"("+_fromDate+ "-" + _toDate +").xls");
			WritableWorkbook book  =  Workbook.createWorkbook(response.getOutputStream());
			WritableSheet sheet =  book.createSheet( "统计( "+warehouseCode+")",0);
			sheet.setColumnView(0, 22);
			sheet.setColumnView(1, 50);
			sheet.setColumnView(2, 20);
			Label label1 = new  Label(0,0 ,"姓名");
			sheet.addCell(label1);
			Label label2 = new  Label(1,0 ,"工序");
			sheet.addCell(label2);
			Label label3 = new  Label(2,0 ,"数量");
			sheet.addCell(label3);
			Label label4 = new  Label(3,0 ,"费用");
			sheet.addCell(label4);
			Label label5 = new  Label(4,0 ,"仓库");
			sheet.addCell(label5);
			Label label6 = new  Label(5,0 ,"客户");
			sheet.addCell(label6);
			for(int i=0;i<listMap.size();i++)
			{
				String customerCode= (String)listMap.get(i).get("customer_code");
				String optype=(String)listMap.get(i).get("optype");
				PerformanceFee pf = performanceFeeService.findPerformanceFee(warehouseCode, customerCode, optype);
				Label labe1 = new  Label(0,i+1 ,(String)listMap.get(i).get("realname"));
				sheet.addCell(labe1);
				Label labe2 = new  Label(1,i+1 ,(String)listMap.get(i).get("optype"));
				sheet.addCell(labe2);
				BigDecimal obj = (BigDecimal)listMap.get(i).get("qty");
				Label labe3 = new  Label(2,i+1 ,obj.toString());
				sheet.addCell(labe3);
				if(null != pf)
				{
					int qty= Integer.parseInt(obj.toString());
					Label labe4 = new  Label(3,i+1 ,qty*pf.getFee()+"");
					sheet.addCell(labe4);
				}
				Label labe5 = new  Label(4,i+1 ,(String)listMap.get(i).get("warehouse_code"));
				sheet.addCell(labe5);
				Label labe6 = new  Label(5,i+1 ,(String)listMap.get(i).get("customer_code"));
				sheet.addCell(labe6);
			}
			book.write();
            book.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadPerformance")
	public Performance getPerformance(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return performanceService.getPerformance(id);
		}
		return null;
	}
	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "checkRealname")
	@ResponseBody
	public String checkLoginName(@RequestParam("realname") String realname) {
		if (accountService.findUserByRealname(realname) == null) {
			return "false";
		} else {
			return "true";
		}
	}
}